const path = require("path");
const execa = require("execa");
const inquirer = require("inquirer");
const menu = require("../shell/menu");
inquirer.registerPrompt("search-list", require("inquirer-search-list"));
const has = (res, key) => Object.prototype.hasOwnProperty.call(res, key);
module.exports = (options) => {
  if (has(options, "select")) {
    let file = path.resolve(__dirname, "../shell/singlePull.sh");
    if (options.select && typeof options.select === "string") {
      let dir = "";
      let desc = "";
      menu.forEach((val) => {
        if (val.name === options.select) {
          dir = val.value.basePath + val.value.path;
          desc = val.value.desc;
        }
      });
      if (dir) {
        console.log(`正在同步${desc}`);
        execa(`call ${file} ${dir} ${desc}`);
      } else {
        console.log(`还未配置${options.select}对应项目目录`);
      }
    } else {
      // 更新指定仓库
      inquirer
        .prompt([
          {
            name: "project",
            type: "search-list",
            message: "请选择需要更新的项目目录",
            choices: menu,
          },
        ])
        .then((res) => {
          let dir = res.project.basePath + res.project.path;
          console.log(`更新${res.project.desc}`);
          execa(`call ${file} ${dir} ${res.project.path}`);
        })
        .catch((err) => {
          console.log(err);
        });
    }
  } else {
    // 更新所有仓库
    let file = path.resolve(__dirname, "../shell/pull.sh");
    execa(`call ${file}`);
  }
};
